package com.qf.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Profile;
import com.qf.pojo.User;
import com.qf.service.ProFileService;
import com.qf.utils.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


/**
 * projectName:my_profile
 * author:luo
 * time:2023/1/30 9:33
 */
@WebServlet("/profileservlet")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class ProfileServlet extends BaseServlet {
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-context.xml");
    ProFileService proFileService = ac.getBean(ProFileService.class);
    public String listProfile(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("error","用户未登录");
            return "/error.jsp";
        }
        //2调用业务逻辑
//        response.setContentType("application/json;charset=UTF-8");
        //获取前端传入的页码大小
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        int page_num=1;//初始页码为1
        int page_size=5;//默认每页显示5条数据
        try {
            if (!StringUtils.isEmpty(pageNum)){
                page_num=Integer.parseInt(pageNum);
                if (page_num<=0){
                    page_num=1;
                }
            }
            if (!StringUtils.isEmpty(pageSize)){
                page_size=Integer.parseInt(pageSize);
                if (page_size<=0){
                    page_size=5;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        PageHelper.startPage(page_num,page_size);
        List<Profile> profileList=proFileService.find();
//        profileList.forEach(profile -> {
//            System.out.println(profile.getBirthday());
//        });
        PageInfo<Profile> pageBean = new PageInfo<Profile>(profileList);
        request.setAttribute("pageBean", pageBean);
        return "/list.jsp";
    }
    public String detailProfile(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("error","用户未登录");
            return "/error.jsp";
        }
        String id = request.getParameter("id");//获取账户id
        //3调用业务逻辑
        //查询该账户详细信息 用实体类承接
        Profile profile=proFileService.getDetail(id);
        request.setAttribute("profile",profile);
        return "/detail.jsp";
    }
    public String loadUpdateInfoProfile(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        //判断用户是否登录
        response.setContentType("text/html;charset=UTF-8");
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("error","用户未登录");
            return "/error.jsp";
        }
        String id = request.getParameter("id");//获取要修改的账户id
        //3调用业务逻辑
        //查询该账户详细信息 用实体类承接
        Profile updateInfo=proFileService.getDetail(id);
        request.setAttribute("updateInfo",updateInfo);
        return "/update.jsp";
    }
    public String updateProfile(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        //1获取前端数据
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            request.setAttribute("error", "用户未登录");
            return "/error.jsp";
        }
        String id = request.getParameter("id");//获取要修改的账户id
        String name = request.getParameter("name");
        String birthday = request.getParameter("birthday");
//        System.out.println("birthday="+birthday);
        String gender = request.getParameter("gender");
        String career = request.getParameter("career");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");
//        String picture = request.getParameter("picture");
        Part picture = request.getPart("picture");

        //3调用业务逻辑
        //处理图片
        //保存图片
        //处理ie浏览器问题
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
        filename = filename.substring(filename.lastIndexOf("\\") + 1);
        String uuidFilename = null;
        if(!filename.equals("")){
            //保存图片
            //生成图片路径
            String basePath = this.getServletContext().getRealPath("WEB-INF"+ File.separator+"images");
            File dir = new File(basePath);
            if(!dir.exists()){
                //创建路径
                dir.mkdirs();
            }
            //获取后缀
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            //随机生成名称
            uuidFilename = UUID.randomUUID().toString().replace("-", "");
            //拼接
            uuidFilename = uuidFilename+"."+ext;
            //上传
            picture.write(basePath+File.separator+uuidFilename);
            //清空缓存
            picture.delete();
//            System.out.println("图片保存成功");
        }
        try {
            //存入实体类
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Profile profile = new Profile(Integer.parseInt(id), name, sdf.parse(birthday), gender, career, address, mobile, uuidFilename);
            proFileService.modify(profile);
            return "profileservlet?method=listProfile";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "修改失败" + e.getMessage());
            return "/error.jsp";
        }
    }
    public String imgProfile(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        //1获取前端数据
        //判断用户是否登录
        request.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            request.setAttribute("msg","用户未登录");
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");//获取账户id
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("error", "id不存在");
            return "/error.jsp";
        }
        //查询该账户详细信息 用实体类承接
        Profile profile= null;
        try {
            profile = proFileService.getDetail(id);
            String basePath=this.getServletContext().getRealPath("WEB-INF"+File.separator+"images"+File.separator+profile.getPicture());
            File file = new File(basePath);
            if(file.exists()){//路径存在
                FileInputStream fis = new FileInputStream(file);
                ServletOutputStream os = response.getOutputStream();
                byte[] buf = new byte[1024*8];
                int len;
                while ((len = fis.read(buf))!=-1){
                    os.write(buf,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","查询失败"+e.getMessage());
            return "/error.jsp";
        }
        return null;
    }
}

